package tt.dz.egobus.servicemanager.business.convert;

import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.converter.Converter;
import tt.dz.egobus.api.managerservice.manager.BusinessCodeServiceStatus;
import tt.dz.egobus.api.managerservice.manager.UserRequestTypeInfo;
import tt.dz.egobus.emuns.OrderSn;
import tt.dz.egobus.servicemanager.entities.BusService;
import tt.dz.egobus.servicemanager.service.BusServiceService;
import tt.dz.egobus.servicemanager.util.PojoConvertVoUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static tt.dz.egobus.emuns.OrderSn.TAKE_DAY;
import static tt.dz.egobus.emuns.OrderSn.TAKE_DAY_HALF;
import static tt.dz.egobus.emuns.OrderSn.TAKE_TIME;

/**
 * @author Anson
 * @date 17-9-1
 * @name 根据请求类别获取起对应的服务说明
 * @since 1.0.7
 */
public class ServiceByRequestType implements Converter<UserRequestTypeInfo.UserRequestType, List<BusinessCodeServiceStatus>> {
    private final ApplicationContext application;

    private static final Map<UserRequestTypeInfo.UserRequestType, List<OrderSn>> REQUEST_TYPE_SERVICE = new HashMap<>();

    static {
        List<OrderSn> bespeakOrderSn = new ArrayList<>();
        bespeakOrderSn.add(TAKE_DAY);
        bespeakOrderSn.add(TAKE_DAY_HALF);

        List<OrderSn> rightNowOrderSn = new ArrayList<>();
        rightNowOrderSn.add(TAKE_TIME);
        rightNowOrderSn.add(TAKE_DAY_HALF);
        REQUEST_TYPE_SERVICE.putIfAbsent(UserRequestTypeInfo.UserRequestType.BESPEAK, bespeakOrderSn);
        REQUEST_TYPE_SERVICE.putIfAbsent(UserRequestTypeInfo.UserRequestType.NOW, rightNowOrderSn);
    }

    public ServiceByRequestType(ApplicationContext applicationContext) {
        this.application = applicationContext;
    }

    @Override
    public List<BusinessCodeServiceStatus> convert(UserRequestTypeInfo.UserRequestType source) {
        BusServiceService busService = this.application.getBean("busServiceServiceImpl", BusServiceService.class);
        Integer[] businessCodes = this.convertCodes(REQUEST_TYPE_SERVICE.get(source));
        List<BusService> busServices = busService.getServices(businessCodes);
        List<BusinessCodeServiceStatus> list = new ArrayList<>();
        if (busServices.isEmpty()) {
            return list;
        }
        for (BusService service : busServices) {
            list.add(PojoConvertVoUtils.busServiceConvertBusinessCodeServiceStatus(service));
        }
        return list;
    }

    /**
     * @param orderSns 服务号枚举
     * @author Anson
     * @date 17-9-1
     * @name 根据服务枚举, 转换成服务号集合
     * @since 1.0.7
     */
    private Integer[] convertCodes(List<OrderSn> orderSns) {
        int count = orderSns.size();
        Integer[] codes = new Integer[count];
        for (int i = 0; i < count; i++) {
            codes[i] = orderSns.get(i).getCode();
        }
        return codes;
    }
}
